function B = slmap(src, dst, A, v0)
%SLMAP Maps old values to new values by table-lookup
%
% [ Syntax ]
%   - B = slmap(src, dst, A)
%   - B = slmap(src, dst, A, v0)
%
% [ Description ]
%   - [B1, B2, ...] = slmap(src, dst, A1, A2, ...) maps the values in Ai to
%     Bi of the same size based on map.
%
%     The mapping is defined by src and dst, which should be both column 
%     vectors and have the same size. All elements in Ai whose
%     values are equal to src(j) are mapped to the values dst(j) in 
%     Bi. 
%
%     The elements whose values that are not defined in map are mapped
%     to zeros.
%
%   - B = slmap(src, dst, A, v0) it maps the all elements that are not 
%     not in src to v0. 
%
% [ History ]
%   - Created by Dahua Lin, on Jan 4, 2008
%

%% parse and verify arguments

assert( ...
    ndims(src) == 2 && ndims(dst) == 2 &&  ...
    size(src, 2) == 1 && size(dst, 2) == 1 && ...
    size(src, 1) == size(dst, 1), ...
    'sltoolbox:slmap:invalidarg', ...
    'Both src and dst should be column vectors of the same length.');

if nargin < 4
    v0 = 0;
else
    assert(isscalar(v0), ...
        'sltoolbox:slmap:invalidarg', ...
        'v0 should be a scalar.');
end


%% main

% group the elements in A

[u, i, j] = unique(A);

% ud: map from u to src

[tf, id] = ismember(u, src);

if size(dst, 2) > 0
    dst = dst';
end

if all(tf)
    ud = dst(id);
else
    ud = zeros(size(u), class(dst));
    ud(tf) = dst(id(tf));
    ud(~tf) = v0;
end

% construct B

B = reshape(ud(j), size(A));

    